package chapter04

/**
 * @program lu-scala01
 * @description:  复杂函数 MapReduce
 *  - map 转换：过滤、map映射、扁平化、扁平映射、分组等
 *  - reduce 简化(归约): 保持一个状态把所有数据做一个统一的处理
 * @author: zhanglu
 * @create: 2022-04-09 10:54:00
 */
object Lu14_ComplexFunction {

  def main(args: Array[String]): Unit = {
    val l01 = List(1, 2, 3, 4, 5, 6, 7, 8, 9)

    /**********************转换**********************/

    //过滤
    println(l01.filter(_ % 2 == 0))

    //map映射
    println(l01.map(_ * 2))
    println(l01.map(x => x * x))

    //扁平化
    val nestedList: List[List[Int]] = List(List(1, 2, 3), List(4, 5, 6), List(7, 8, 9))
    println(nestedList.flatten)

    //扁平映射
    val strs: List[String] = List("hello world", "hello scala", "hello java", "hello lu")
    val splitList: List[Array[String]] = strs.map(_.split(" "))
    println(splitList.flatten)
    //等价于
    println(strs.flatMap(_.split(" ")))

    //分组
    println(l01.groupBy(_ % 2))
    val groupMap: Map[String, List[Int]] = l01.groupBy(x => if (x % 2 == 0) "偶数" else "奇数")
    println(groupMap)

    //首字母分组
    val worldList = List("china", "america", "alice", "canada", "cary", "bob", "japan")
    println(worldList.groupBy(_.charAt(0)))

    /**********************规约**********************/
    println("=============")

    val l02 = List(3, 4, 5, 8, 10)

    //reduce
    println(l02.reduce(_ + _))
    println(l02.reduceLeft(_ + _))
    println(l02.reduceRight(_ + _))

    println(l02.reduce(_ - _))
    println(l02.reduceLeft(_ - _))  //运行逻辑：3-4-5-8-10 = -24
    println(l02.reduceRight(_ - _)) //运行逻辑：3-(4-(5-(8-10))) = 6

    //折叠
    println(l02.fold(-1)(_ + _))  //-1+3+4+5+8+10
    println(l02.foldLeft(30)(_ - _))  //24-3-4-5-8-10
    println(l02.foldRight(6)(_ - _)) //3-(4-(5-(8-(10-6))))

  }

}
